package com.moji.common.base;

import com.baomidou.mybatisplus.extension.api.IErrorCode;
import com.moji.util.ResultCode;
import lombok.Data;
import lombok.experimental.Accessors;

import java.util.Optional;

@Data
@Accessors(chain = true)
public class ApiResult<T> {

	private static final long serialVersionUID = 1L;

	/**
	 * 业务错误码
	 */
	private long code;
	/**
	 * 结果集
	 */
	private T data;
	/**
	 * 描述
	 */
	private String msg;

	public ApiResult() {
		// to do nothing
	}

	public ApiResult(IErrorCode errorCode) {
		errorCode = Optional.ofNullable(errorCode).orElse(ResultCode.FAILED);
		this.code = errorCode.getCode();
		this.msg = errorCode.getMsg();
	}

	public static <T> ApiResult<T> ok(T data) {
		return restResult(data, ResultCode.SUCCESS);
	}

	public static <T> ApiResult<T> failed(String msg) {
		return restResult(null, ResultCode.FAILED.getCode(), msg);
	}

	public static <T> ApiResult<T> routerFailed(String msg) {
		return restResult(null, ResultCode.ROUTER_IS_NULL.getCode(), msg);
	}
	public static <T> ApiResult<T> failed(T data) {
		return restResult(data, ResultCode.FAILED.getCode(), ResultCode.FAILED.getMsg());
	}

	public static <T> ApiResult<T> failed(IErrorCode errorCode) {
		return restResult(null, errorCode);
	}

	public static <T> ApiResult<T> restResult(T data, IErrorCode errorCode) {
		return restResult(data, errorCode.getCode(), errorCode.getMsg());
	}

	private static <T> ApiResult<T> restResult(T data, long code, String msg) {
		ApiResult<T> apiResult = new ApiResult<T>();
		apiResult.setCode(code);
		apiResult.setData(data);
		apiResult.setMsg(msg);
		return apiResult;
	}

}